﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AntiObesity.Base;
using AntiObesity.Base.Managers;

namespace AntiObesity.Services
{
    [WebService(Namespace = "http://antiobesity-project.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class FoodNameAutoComplete : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var partOfName = context.Request["q"];
            var limit = Convert.ToInt32(context.Request["limit"]);
            if (limit > 20)
                limit = 20;
            var foods = FoodManager.FindByNameSimilarity(partOfName, limit);

            foreach (var food in foods)
            {
                var output = String.Format("match:'{0}', id: '{1}', name:'{2}'", 
                    food.Name.Replace(partOfName, "<b>" + partOfName + "</b>").Replace("'",@"\'"),
                    food.ID,
                    food.Name.Replace("'", @"\'"));
                output = "{" + output + "}";
                context.Response.Write(output + Environment.NewLine);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}
